package org.example.oauth.service;


import org.example.oauth.entity.TPermission;
import org.example.oauth.entity.TUser;
import org.example.oauth.mapper.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class UserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TUserMapper tUserMapper;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser =  tUserMapper.findByUserName(username);
        List<String> permissions = new ArrayList<>();
        if (tUser!=null){
            List<TPermission> tPermissionList =  tUserMapper.findPermissionByUserId(tUser.getId());
            if (!tPermissionList.isEmpty()){
                tPermissionList.forEach(tp->permissions.add( tp.getCode() ) );
            }
        }
        String[] perimArry = new String[permissions.size()];
        permissions.toArray(perimArry);
        UserDetails userDetails = User.withUsername(tUser.getUsername() ).password(tUser.getPassword()).authorities(perimArry).build();
        return userDetails;
    }
}
